<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>编辑维修单</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-divider content-position="left">报修信息</el-divider>
        <el-form-item label="报修单号">
          <el-input v-model="form.orderCode" disabled />
        </el-form-item>
        
        <el-form-item label="设备名称">
          <el-input v-model="form.equipmentName" disabled />
        </el-form-item>
        
        <el-form-item label="设备编号">
          <el-input v-model="form.equipmentCode" disabled />
        </el-form-item>
        
        <el-divider content-position="left">维修信息</el-divider>
        <el-form-item label="维修单号">
          <el-input v-model="form.recordCode" disabled />
        </el-form-item>
        
        <el-form-item label="维修人员" prop="repairBy">
          <el-input v-model="form.repairBy" placeholder="请输入维修人员" />
        </el-form-item>
        
        <el-form-item label="维修日期" prop="repairDate">
          <el-date-picker
            v-model="form.repairDate"
            type="date"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            placeholder="请选择维修日期">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="维修结果" prop="repairResult">
          <el-input v-model="form.repairResult" type="textarea" rows="3" placeholder="请输入维修结果" />
        </el-form-item>
        
        <el-form-item label="维修状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择维修状态" style="width: 100%">
            <el-option label="待处理" value="0" />
            <el-option label="处理中" value="1" />
            <el-option label="已完成" value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="维修费用" prop="repairCost">
          <el-input-number v-model="form.repairCost" :min="0" :precision="2" :step="100" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        
        <el-divider content-position="left">配件信息</el-divider>
        <div class="component-list">
          <el-table :data="form.components" border style="width: 100%">
            <el-table-column prop="componentName" label="配件名称" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.componentName" placeholder="请输入配件名称"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="componentCode" label="配件编号" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.componentCode" placeholder="请输入配件编号"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" align="center" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" :precision="0" :step="1" @change="updateTotalPrice(scope.$index)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" align="center" width="150">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2" :step="10" @change="updateTotalPrice(scope.$index)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="总价" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.totalPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="removeComponent(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addComponent">添加配件</el-button>
          </div>
        </div>
        
        <div style="margin-top: 20px; text-align: center;">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="goBack">取 消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getRepairRecord, updateRepairRecord } from "@/api/sb/repairRecord";

export default {
  name: "EditRepairRecord",
  data() {
    return {
      // 表单参数
      form: {
        id: null,
        recordCode: "",
        orderCode: "",
        equipmentId: null,
        equipmentName: "",
        equipmentCode: "",
        repairBy: "",
        repairDate: "",
        repairResult: "",
        repairCost: 0,
        status: "",
        remark: "",
        components: []
      },
      // 表单校验
      rules: {
        repairBy: [
          { required: true, message: "请输入维修人员", trigger: "blur" }
        ],
        repairDate: [
          { required: true, message: "请选择维修日期", trigger: "change" }
        ],
        repairResult: [
          { required: true, message: "请输入维修结果", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择维修状态", trigger: "change" }
        ]
      }
    };
  },
  created() {
    const id = this.$route.params.id;
    this.getDetail(id);
  },
  methods: {
    /** 获取详细信息 */
    getDetail(id) {
      getRepairRecord(id).then(response => {
        this.form = response.data;
        
        // 确保components存在
        if (!this.form.components) {
          this.form.components = [];
        }
      });
    },
    /** 添加配件 */
    addComponent() {
      this.form.components.push({
        componentName: "",
        componentCode: "",
        quantity: 1,
        unitPrice: 0,
        totalPrice: 0
      });
    },
    /** 移除配件 */
    removeComponent(index) {
      this.form.components.splice(index, 1);
      this.calculateTotalCost();
    },
    /** 更新总价 */
    updateTotalPrice(index) {
      const component = this.form.components[index];
      component.totalPrice = (component.quantity * component.unitPrice).toFixed(2);
      this.calculateTotalCost();
    },
    /** 计算总费用 */
    calculateTotalCost() {
      let total = 0;
      this.form.components.forEach(item => {
        total += Number(item.totalPrice);
      });
      this.form.repairCost = total;
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查配件信息完整性
          for (let i = 0; i < this.form.components.length; i++) {
            const component = this.form.components[i];
            if (!component.componentName || !component.componentCode) {
              this.$modal.msgError("请填写完整的配件信息");
              return;
            }
            // 确保总价正确
            component.totalPrice = (component.quantity * component.unitPrice).toFixed(2);
          }
          
          // 如果状态从处理中变为已完成，记录完成时间
          if (this.form.status === "2" && !this.form.finishTime) {
            this.form.finishTime = this.parseTime(new Date());
          }
          
          updateRepairRecord(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.goBack();
          });
        }
      });
    },
    /** 返回按钮操作 */
    goBack() {
      this.$router.push("/sb/repair-record");
    }
  }
};
</script>

<style scoped>
.component-list {
  margin-bottom: 20px;
}
</style> 